package com.moseph.qrsqueeze;

import java.awt.BorderLayout;
import java.util.*;

import javax.swing.JFrame;

import org.bff.slimserver.*;
import org.bff.slimserver.exception.*;
import org.bff.slimserver.musicobjects.*;

import processing.core.PImage;

import com.google.zxing.*;

public class QRSqueeze extends QRReader
{
	String hostname = "mo-seph.no-ip.org";
    String playerName = "Living Room";
	SlimServer ss = null;
    int cliPort = 9090;
    int webPort = 9000;
    SlimPlayer player = null;
	private SlimDatabase database;
	String lastLookup = "";
	private SlimPlaylist playlist;
	long lastSeenTime = 0;
	private PImage image;
	private ResultPoint currentPoint;
	private SlimAlbum currentAlbum = null;
    
	public static void main( String[] args ) 
	{
		JFrame f = new JFrame( "QR SqueezePlayer Capture" );
		f.setLayout( new BorderLayout() );
		QRSqueeze reader = new QRSqueeze();
		f.add( reader );
		reader.init();
		f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		f.setSize( imgWidth, imgHeight );
		f.setVisible( true );
		
		/*
		try
		{
			reader.setupSlimConnection();
			for( SlimAlbum a : reader.database.searchAlbums( "isam" ) )
				System.out.println( a.getName() + "::" + a.getArtist() );
		} catch (SlimDatabaseException e) { e.printStackTrace(); }
		*/
	}
	
	public void init()
	{
		super.init();
		drawImage = true;
		drawPoints = true;
		setupSlimConnection();
	}
	
	public void setupSlimConnection() {

        try {
            SlimServer ss = new SlimServer(hostname, cliPort, webPort);
            System.out.println("is connected:" + ss.isConnected());
			database = new SlimDatabase( ss );
	        List<SlimPlayer> players = new ArrayList<SlimPlayer>(ss.getSlimPlayers());
	        for (SlimPlayer p : players)
	        {
	            System.out.println("\t" + p.getName());
	        	if( p.getName().equalsIgnoreCase( playerName ))
	        	{
	        		player = p;
					playlist = ss.getSlimPlaylist( player );
					System.out.println( "Connected to player: " + player.getName() );
	        	}
	        }
	        if( player == null )
	        {
	        	System.out.println( "Player not found: " + playerName );
	        }
	        
        } catch (SlimConnectionException ex) {
            System.out.println("There was a problem connecting to SqueezeCenter!");
            System.out.println( ex );
            ss = null;
        }
    }
	
	public void draw()
	{
		super.draw();
		if( currentPoint != null && image != null )
		{
	        image(image, currentPoint.getX(), currentPoint.getY(), 200, 200 );
		}
	}
	
	public void processResult( Result r ) 
	{
		if( r.getText() != null && r.getText().length() > 0 )
		{
			currentPoint = r.getResultPoints()[1];
			
			if( ! r.getText().equals( lastLookup ) )
			{
				try
				{
					System.out.println( "Searching for currentAlbum: '" + r.getText() + "'");
					Collection<SlimAlbum> albums = database.searchAlbums( r.getText() );
					currentAlbum = albums.iterator().next();
					System.err.println( "Image URL: " + currentAlbum.getImageUrl() );
					image = loadImage( currentAlbum.getImageUrl().toString() );
				} catch (SlimDatabaseException e)
				{
					System.err.println( "Couldn't search database: " + e );
				} 
			}
			if( ! r.getText().equals( lastLookup ) || System.currentTimeMillis() - lastSeenTime > 5000 )
			{
				try
				{
					System.out.println( "Playing: " + currentAlbum.getName() + " by " + currentAlbum.getArtist() );
					player.stop();
					playlist.clear();
					playlist.addAlbum( currentAlbum );
					player.play();
				}
				catch (SlimException e)
				{
					System.err.println( "Couldn't play: " + e );
				}
			}
			lastLookup = r.getText();
			lastSeenTime = System.currentTimeMillis();
		}
	}
	
	public void notFound()
	{
		currentPoint = null;
	}
	
	public void createPlaylist(SlimServer ss, SlimPlayer player) {
        try {
            SlimPlaylist playlist = ss.getSlimPlaylist(player);

            SlimDatabase database = new SlimDatabase(ss);
            List<SlimArtist> artists = new ArrayList<SlimArtist>(database.searchArtists("Metallica"));
            List<SlimSong> songs = new ArrayList<SlimSong>(database.listSongsForArtist(artists.get(0)));
            playlist.addItem( songs.get( 0 ) );

        } catch (Exception ex) {
            System.out.println("There was a problem connecting to SqueezeCenter!");
            System.out.println( ex );
        }
    }

}
